package cn.leonis.leetcode;

import java.util.HashSet;
import java.util.Set;

/**
 * @Author Tobi
 * @Date 2021-07-22 下午9:24
 * 环形链表
 */
public class LinkedListCycleSolution {

    public static void main(String[] args) {

    }

    /**
     * 判断是否环形链表，解法一，哈希表法，判断是否存在值
     * @param head 头结点
     * @return
     */
    public boolean hasCycle(ListNode head) {

        if (head == null || head.next == null) {
            return false;
        }

        Set<ListNode> nodeSet = new HashSet<>();

        while (head != null) {
            if (!nodeSet.add(head)) {
                return true;
            }
            // 指向下一个指针
            head = head.next;
        }

        return false;

    }


    /**
     * 快慢指针法，龟兔赛跑算法
     * @param head
     * @return
     */
    public boolean hasCycle1(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }
        ListNode slow = head;
        ListNode fast = head.next;
        while (head != fast) {
            if (fast == null || fast.next == null) {
                return false;
            }
            slow = slow.next;
            fast = fast.next.next;
        }

        return true;
    }
}
